package com.netbetter.langzheng.commons.gears.innerbo.impl;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.gears.client.database.Database;
import com.google.gwt.gears.client.database.DatabaseException;
import com.google.gwt.gears.client.database.ResultSet;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.netbetter.langzheng.commons.gears.dto.SqlStateDTO;
import com.netbetter.langzheng.commons.gears.innerbo.Json2GearsBO;
import com.netbetter.langzheng.commons.gears.utils.GearsUtils;

/**
 * 将json格式转换为gears数据格式
 * 
 * @author jim
 */
public class Json2GearsBOImpl implements Json2GearsBO {

  private String tableName;
  private JSONArray jsonArray;
  private Database localDB;

  public String getTableName() {
    return tableName;
  }

  public void setTableName(String tableName) {
    this.tableName = tableName;
  }

  public JSONArray getJsonArray() {
    return jsonArray;
  }

  public void setJsonArray(JSONArray jsonArray) {
    this.jsonArray = jsonArray;
  }

  public boolean convertData2Gears() throws DatabaseException {

    createTableByJsonObject(jsonArray.get(0).isObject());
    for (int i = 0; i < jsonArray.size(); i++) {
      insertJsonObject(jsonArray.get(i).isObject());
    }
    return true;
  }

  /**
   * 以jsonObject创建gears数据格式
   * 
   * @param jsonObject
   * @throws DatabaseException
   */
  private void createTableByJsonObject(JSONObject jsonObject)
      throws DatabaseException {
    SqlStateDTO sqlDto = GearsUtils.getCreateSqlByJSONObject(tableName,
        jsonObject);
    localDB.execute(sqlDto.getSql());
    if (Log.isDebugEnabled()) {
      boolean isOk = false;
      try {
        ResultSet rs = localDB.execute("select * from " + tableName);
        rs.close();
        isOk = true;
      } catch (DatabaseException error) {
        Log.error("create table error  sql:", error);
      }
      if (isOk) {
        Log.debug("create table OK  sql:" + sqlDto.getSql());
      } else {
        Log.error("create table Error  sql:" + sqlDto.getSql());
      }
    }
  }

  /**
   * 插入json到gears中
   * 
   * @param jsonObject
   * @throws DatabaseException
   */
  private void insertJsonObject(JSONObject jsonObject) throws DatabaseException {
    String id = jsonObject.get("id").toString();
    SqlStateDTO sqlDto = GearsUtils.getInsertSqlByJSONObject(tableName,
        jsonObject);
    try {
      localDB.execute(sqlDto.getSql(), sqlDto.getValues());
    } catch (DatabaseException error) {
      Log.error("excute error", error);
    }
    if (Log.isDebugEnabled()) {
      boolean isOk = false;
      ResultSet rs = localDB.execute("select * from " + tableName
          + " where id=?", new String[] {id});
      for (int i = 0; rs.isValidRow(); ++i, rs.next()) {
        if (rs.getFieldAsString(0) != null) {
          isOk = true;
        }
      }
      rs.close();
      StringBuffer valusBuffer = new StringBuffer();
      for (int i = 0; i < sqlDto.getValues().length; i++) {
        valusBuffer.append(sqlDto.getValues()[i]).append(",");
      }
      if (isOk) {
        Log.debug("insert ok sql:" + sqlDto.getSql() + " values:"
            + valusBuffer.toString());
      } else {
        Log.error("insert error sql:" + sqlDto.getSql() + " values:"
            + valusBuffer.toString());
      }
    }

  }

  public Database getLocalDB() {
    return localDB;
  }

  public void setLocalDB(Database localDB) {
    this.localDB = localDB;
  }
}
